﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContexts.Supplier;

public partial class Controls_SearchControl : System.Web.UI.UserControl
{
    private SupplierDataContext supplierContext = new SupplierDataContext();

    public int CountryId
    {
        get { return Helper.QSIntValue("cid"); }
    }
    public int RegionId
    {
        get { return Helper.QSIntValue("rid"); }
    }
    public int LocationId
    {
        get { return Helper.QSIntValue("lid"); }
    }
    public DateTime PickUpDate
    {
        get { return Helper.QSDateValue("pdt"); }
    }
    public DateTime DropDate
    {
        get { return Helper.QSDateValue("ddt"); }
    }
    public decimal PickUpTime
    {
        get { return Helper.QSDecimalValue("pt"); }
    }
    public decimal DropTime
    {
        get { return Helper.QSDecimalValue("dt"); }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadCountries();
            ddlRegion.Items.Insert(0, new ListItem("--Select Region--", "0"));
            ddlLocation.Items.Insert(0, new ListItem("--Select Location--", "0"));
            LoadTimeDropdowns();
            if (CountryId > 0)
            {
                ddlCountry.SelectedValue = CountryId.ToString();
                LoadRegions(CountryId);
            }
            if (RegionId > 0)
            {
                ddlRegion.SelectedValue = RegionId.ToString();
                LoadLocations(RegionId);
            }
            if (LocationId > 0)
                ddlLocation.SelectedValue = LocationId.ToString();

            if (PickUpDate != DateTime.MinValue)
                dtpStartDate.SelectedDate = PickUpDate;

            if (DropDate != DateTime.MinValue)
                dtpEndDate.SelectedDate = DropDate;

            if (PickUpTime > 0)
                ddlStartTime.SelectedValue = PickUpTime.ToString(Constants.DECIMAL_FORMAT);

            if (DropTime > 0)
                ddlEndTime.SelectedValue = DropTime.ToString(Constants.DECIMAL_FORMAT);
        }
    }

    private void LoadTimeDropdowns()
    {
        ddlStartTime.Items.Clear();
        ddlEndTime.Items.Clear();
        decimal Start = 6.0M;
        string pre = "";
        string post = "";
        while (Start < 19.0M)
        {
            pre = Math.Floor(Start).ToString("00");
            post = ".00";
            if (Start % 1 == 0.5M)
            {
                post = ".30";
            }
            ddlStartTime.Items.Add(pre + post);
            ddlEndTime.Items.Add(pre + post);

            Start += 0.5M;
        }
    }


    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCountry.SelectedIndex > 0)
        {
            LoadRegions(Convert.ToInt32(ddlCountry.SelectedValue));
        }
    }
    protected void ddlRegion_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlRegion.SelectedIndex > 0)
        {
            LoadLocations(Convert.ToInt32(ddlRegion.SelectedValue));
        }
    }
    protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (ddlLocation.SelectedIndex > 0)
        //{
        //    GenerateStartTimeDropDownItems(Convert.ToInt32(ddlLocation.SelectedValue));
        //    GenerateEndTimeDropDownItems(Convert.ToInt32(ddlLocation.SelectedValue));
        //}
    }

    private void GenerateStartTimeDropDownItems(int locationID)
    {
        DateTime currentdate = DateTime.Now;
        int dayOfWeek = (int)currentdate.DayOfWeek;

        string startTimeFrom = (from st in supplierContext.SupplierLocationTimes
                                where st.LocationId == Convert.ToInt32(locationID) && st.Day == dayOfWeek
                                select st.StartTime).Min().ToString();

        string startTimeTo = (from st in supplierContext.SupplierLocationTimes
                              where st.LocationId == Convert.ToInt32(locationID) && st.Day == dayOfWeek
                              select st.StartTime).Max().ToString();


        DateTime dt = DateTime.Now;
        var newdt = dt.Date + TimeSpan.FromHours(Convert.ToDouble(startTimeFrom));
        var newdt1 = dt.Date + TimeSpan.FromHours(Convert.ToDouble(startTimeTo));
        var hours = (newdt1 - newdt).TotalHours;
        double loopEndLimit = (double)(hours * 60) / 30;

        double fraction = loopEndLimit - (int)loopEndLimit;
        if (fraction > 0)
        {
            loopEndLimit += 1;
        }

        //Set up every 30 minute interval
        for (double i = 0; i <= loopEndLimit; i++)
        {
            ListItem ddlItem = new ListItem();
            ddlItem.Text = string.Format("{0:HH.mm}", newdt);
            ddlItem.Value = string.Format("{0:HH.mm}", newdt);
            ddlStartTime.Items.Add(ddlItem);
            newdt = newdt.AddMinutes(30);
        }
    }

    private void GenerateEndTimeDropDownItems(int locationID)
    {
        DateTime currentdate = DateTime.Now;
        int dayOfWeek = (int)currentdate.DayOfWeek;

        string endTimeFrom = (from st in supplierContext.SupplierLocationTimes
                              where st.LocationId == Convert.ToInt32(locationID) && st.Day == dayOfWeek
                              select st.StartTime).Min().ToString();

        string endTimeTo = (from st in supplierContext.SupplierLocationTimes
                            where st.LocationId == Convert.ToInt32(locationID) && st.Day == dayOfWeek
                            select st.EndTime).Max().ToString();


        DateTime dt = DateTime.Now;
        var newdt = dt.Date + TimeSpan.FromHours(Convert.ToDouble(endTimeFrom));
        var newdt1 = dt.Date + TimeSpan.FromHours(Convert.ToDouble(endTimeTo));
        var hours = (newdt1 - newdt).TotalHours;
        double loopEndLimit = (double)(hours * 60) / 30;

        double fraction = loopEndLimit - (int)loopEndLimit;
        if (fraction > 0)
        {
            loopEndLimit += 1;
        }

        //Set up every 30 minute interval
        for (double i = 0; i <= loopEndLimit; i++)
        {
            ListItem ddlItem = new ListItem();
            ddlItem.Text = string.Format("{0:HH.mm}", newdt);
            ddlItem.Value = string.Format("{0:HH.mm}", newdt);
            ddlEndTime.Items.Add(ddlItem);
            newdt = newdt.AddMinutes(30);
        }
    }

    #region LoadDropDown Methods
    private void LoadCountries()
    {
        ddlCountry.DataSource = supplierContext.Countries;
        ddlCountry.DataTextField = "CountryName";
        ddlCountry.DataValueField = "CountryId";
        ddlCountry.DataBind();

        ddlCountry.Items.Insert(0, new ListItem("--Select Country--", "0"));
    }

    private void LoadRegions(int countryID)
    {
        ddlRegion.DataSource = from r in supplierContext.Regions
                               where r.CountryId == Convert.ToInt32(countryID)
                               select r;
        ddlRegion.DataTextField = "RegionName";
        ddlRegion.DataValueField = "RegionId";
        ddlRegion.DataBind();

        ddlRegion.Items.Insert(0, new ListItem("--Select Region--", "0"));
    }

    private void LoadLocations(int regionID)
    {
        ddlLocation.DataSource = from l in supplierContext.Locations
                                 where l.RegionId == Convert.ToInt32(regionID)
                                 select l;
        ddlLocation.DataTextField = "LocationName";
        ddlLocation.DataValueField = "LocationId";
        ddlLocation.DataBind();

        ddlLocation.Items.Insert(0, new ListItem("--Select Location--", "0"));
    }
    #endregion

    protected void btnGetQuote_Click(object sender, ImageClickEventArgs e)
    {
        if (Page.IsValid)
        {
            string url = "searchresult.aspx?" +
               "cid=" + ddlCountry.SelectedValue +
               "&rid=" + ddlRegion.SelectedValue +
               "&lid=" + ddlLocation.SelectedValue +
               "&pdt=" + dtpStartDate.getSelectedDate.ToString(Constants.QS_DATE_FORMAT) +
               "&ddt=" + dtpEndDate.getSelectedDate.ToString(Constants.QS_DATE_FORMAT) +
               "&pt=" + ddlStartTime.SelectedValue +
               "&dt=" + ddlEndTime.SelectedValue;

            Response.Redirect(url);
        }

    }

    protected void cvPickUpDate_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (string.IsNullOrEmpty(ddlStartTime.SelectedValue) ||
            string.IsNullOrEmpty(ddlEndTime.SelectedValue))
        {
            args.IsValid = false;
        }
        else
        {
            DateTime endDateTime = dtpEndDate.getSelectedDate + TimeSpan.FromHours(Convert.ToDouble(ddlStartTime.SelectedValue));
            DateTime startDateTime = dtpStartDate.getSelectedDate + TimeSpan.FromHours(Convert.ToDouble(ddlEndTime.SelectedValue));


            TimeSpan noOfDays = endDateTime - startDateTime;

            if (noOfDays.Days == 0 && noOfDays.Hours == 0 && noOfDays.Minutes == 0)
            {
                args.IsValid = false;
            }
        }
    }
}
